package com.kot.backend.service.impl.user.account;

import com.kot.backend.pojo.User;
import com.kot.backend.service.impl.utils.UserDetailsImpl;
import com.kot.backend.service.user.account.LoginService;
import com.kot.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

//把从数据库拿到的用户名密码转成JWT并返回
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public Map<String, String> getToken(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);//把用户名和密码封成对象，里面没有明文，是加密的字符串

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);//验证登录；tips:在函数后加.var回车，会自动补全变量定义；//若登陆失败，会自动处理，未报异常就是登录成功
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();//这两步用于取出用户
        String jwt = JwtUtil.createJWT(user.getId().toString());//把用户id封装成jwt-token

        Map<String, String> map = new HashMap<>();
        map.put("error_message", "success");//返回成功提示
        map.put("token", jwt);//返回id的jwt

        return map;
    }

}
